package com.xuxin.nantai.activity.pack;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.king.zxing.Intents;
import com.xuxin.nantai.R;
import com.xuxin.nantai.activity.MyCaptureActivity;
import com.xuxin.nantai.activity.quan.DefectActivity;
import com.xuxin.nantai.base.BaseActivity;
import com.xuxin.nantai.base.BaseConstant;
import com.xuxin.nantai.base.BaseTextWatcher;
import com.xuxin.nantai.bean.AllAreaBean;
import com.xuxin.nantai.bean.BaseBean;
import com.xuxin.nantai.bean.HangUpdateLoginBean;
import com.xuxin.nantai.bean.PackInfoBean;
import com.xuxin.nantai.contract.AllAreaContract;
import com.xuxin.nantai.contract.PackUpdateContract;
import com.xuxin.nantai.presenter.AllAreaPresenter;
import com.xuxin.nantai.presenter.PackUpdatePresenter;
import com.xuxin.nantai.utils.ACache;
import com.xuxin.nantai.utils.FlowingUtils;
import com.xuxin.nantai.utils.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020.06.22 0022
 * 包装巡检新增修改
 */
public class PackUpdateActivity extends BaseActivity implements PackUpdateContract.View, AllAreaContract.View {
    private PackUpdateContract.Presenter presenter = new PackUpdatePresenter(this);
    private AllAreaContract.Presenter presenter2 = new AllAreaPresenter(this);
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;

    @BindView(R.id.pack_update_flowing)
    EditText pack_update_flowing;//流转单号
    @BindView(R.id.pack_update_name)
    TextView pack_update_name;//成品名称
    @BindView(R.id.pack_update_pack)
    TextView pack_update_pack;//本包数
    @BindView(R.id.pack_update_color)
    EditText pack_update_color;//颜色
    @BindView(R.id.pack_update_percent)
    EditText pack_update_percent;//抽检比例
    @BindView(R.id.pack_update_area)
    TextView pack_update_area;//厂区
    @BindView(R.id.pack_update_check)
    TextView pack_update_check;//抽检数
    @BindView(R.id.pack_update_defect)
    TextView pack_update_defect;//疵点数
    @BindView(R.id.pack_update_inspector)
    TextView pack_update_inspector;//巡检员
    @BindView(R.id.pack_update_reCheck)
    CheckBox pack_update_reCheck;//是否复检
    @BindView(R.id.pack_update_time)
    TextView pack_update_time;//检验日期
    @BindView(R.id.pack_update_result)
    TextView pack_update_result;//判定结果
    @BindView(R.id.pack_update_mark)
    EditText pack_update_mark;//备注
    @BindView(R.id.pack_update_desc)
    TextView pack_update_desc;//疵点描述

    private String Guid;//唯一Guid
    private String ID;//唯一ID
    private String cInvCode;//成品编码
    private String cInvName;//成品名称
    private String Color;//颜色
    private String PackQty;//本包数
    private String Check_BZ;//抽检比例
    private String CheckNum;//抽检数
    private String FlowingCode;//流转单号
    private String Remark;//备注
    private String Result;//判定结果
    private String InspectorCode;//巡检员代码
    private String InspectorName;//巡检员姓名
    private String InspectTime;//检验日期
    private String FacArea;//厂区
    private String DefectNum;//疵点数量
    private String DefectDes;//疵点描述
    private int IsReCheck;//是否复检(是：1，否：0)

    private MaterialDialog materialDialog;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_pack_update);
    }

    @Override
    public void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle && !StringUtils.isEmpty(bundle.getString("Guid"))) {
            title_name.setText("包装巡检修改");
            Guid = bundle.getString("Guid");
            ID = bundle.getString("ID");
            cInvCode = bundle.getString("cInvCode");
            cInvName = bundle.getString("cInvName");
            Color = bundle.getString("Color");
            PackQty = bundle.getString("PackQty");
            Check_BZ = bundle.getString("Check_BZ");
            CheckNum = bundle.getString("CheckNum");
            FlowingCode = bundle.getString("FlowingCode");
            Remark = bundle.getString("Remark");
            Result = bundle.getString("Result");
            InspectorCode = bundle.getString("InspectorCode");
            InspectorName = bundle.getString("InspectorName");
            InspectTime = bundle.getString("InspectTime");
            FacArea = bundle.getString("FacArea");
            DefectNum = bundle.getString("DefectNum");
            DefectDes = bundle.getString("DefectDes");
            IsReCheck = bundle.getInt("IsReCheck");

            pack_update_flowing.setText(FlowingCode);
            pack_update_name.setText(cInvName);
            pack_update_pack.setText(PackQty);
            pack_update_color.setText(Color);
            pack_update_percent.setText(Check_BZ);
            pack_update_area.setText(FacArea);
            pack_update_check.setText(CheckNum);
            pack_update_defect.setText(DefectNum);
            pack_update_inspector.setText(InspectorName);
            pack_update_reCheck.setChecked(1 == IsReCheck);
            pack_update_time.setText(InspectTime);
            pack_update_result.setText(Result);
            pack_update_mark.setText(Remark);
            pack_update_desc.setText(DefectDes);
            pack_update_percent.addTextChangedListener(new myTextWatcher());
            LogUtils.e("包装巡检修改_Guid = " + Guid);
        } else {
            title_name.setText("包装巡检新增");
            LogUtils.e("包装巡检新增_Guid = " + Guid);
            InspectorCode = ACache.get(this).getAsString("LoginName");
            InspectorName = ACache.get(this).getAsString("UserName");
            pack_update_inspector.setText(InspectorName);
        }
        //新增
        if (StringUtils.isEmpty(Guid)) {
            //默认日期今天
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            Date date = new Date(System.currentTimeMillis());
            InspectTime = simpleDateFormat.format(date);
            pack_update_time.setText(InspectTime);
            //给个默认的判定结果
            Result = "合格";
            pack_update_result.setText(Result);
        }
    }

    @Override
    public void initData() {
        if (StringUtils.isEmpty(Guid)) {
            //新增给个默认厂区
            handler.sendEmptyMessage(1);//给个默认厂区
        }
        handler.sendEmptyMessage(2);//所有厂区列表
    }

    @Override
    public void onComplete() {
        if (null != materialDialog) {
            materialDialog.dismiss();
        }
    }

    @Override
    @OnClick({R.id.title_left, R.id.pack_update_search, R.id.pack_update_scan,
            R.id.pack_update_time, R.id.pack_update_result, R.id.pack_update_gain,
            R.id.pack_update_update, R.id.pack_update_area})
    public void onClick(View view) {
        KeyboardUtils.hideSoftInput(this);
        switch (view.getId()) {
            case R.id.title_left:
                finish();
                break;
            case R.id.pack_update_search:
                FlowingCode = pack_update_flowing.getText().toString();
                if (StringUtils.isEmpty(FlowingCode)) {
                    ToastUtils.showShort("请输入流转单号");
                    return;
                }
                handler.sendEmptyMessage(0);
                break;
            case R.id.pack_update_scan:
                startActivityForResult(new Intent(this, MyCaptureActivity.class), BaseConstant.result_scan);
                break;
            case R.id.pack_update_time:
                TimeUtils.showDate(this, time -> {
                    InspectTime = time;
                    pack_update_time.setText(InspectTime);
                });
                break;
            case R.id.pack_update_result:
                new MaterialDialog.Builder(this)
                        .items("合格", "不合格")
                        .itemsCallback((dialog, view1, position, text) -> {
                            try {
                                Result = (0 == position) ? "合格" : "不合格";
                                pack_update_result.setText(Result);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        })
                        .show();
                break;
            case R.id.pack_update_gain:
                try {
                    Bundle bundle = new Bundle();
                    bundle.putString("Guid", Guid);
                    bundle.putString("InsType", "包装");
                    ActivityUtils.startActivityForResult(bundle, this,
                            DefectActivity.class, BaseConstant.result_code);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.pack_update_update:
                try {
                    FlowingCode = pack_update_flowing.getText().toString();
                    cInvName = pack_update_name.getText().toString();
                    PackQty = pack_update_pack.getText().toString();
                    Color = pack_update_color.getText().toString();
                    Check_BZ = pack_update_percent.getText().toString();
                    FacArea = pack_update_area.getText().toString();
                    CheckNum = pack_update_check.getText().toString();
                    DefectNum = pack_update_defect.getText().toString();
                    InspectorName = pack_update_inspector.getText().toString();
                    IsReCheck = pack_update_reCheck.isChecked() ? 1 : 0;
                    InspectTime = pack_update_time.getText().toString();
                    Result = pack_update_result.getText().toString();
                    Remark = pack_update_mark.getText().toString();
                    DefectDes = pack_update_desc.getText().toString();
                    if (StringUtils.isEmpty(FlowingCode)) {
                        ToastUtils.showShort("请输入流转单号");
                        return;
                    }
                    if (StringUtils.isEmpty(cInvName)) {
                        ToastUtils.showShort("成品名称不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(PackQty)) {
                        ToastUtils.showShort("本包数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(Color)) {
                        ToastUtils.showShort("请输入颜色");
                        return;
                    }
                    if (StringUtils.isEmpty(Check_BZ)) {
                        ToastUtils.showShort("抽检比例不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(FacArea)) {
                        ToastUtils.showShort("请输入厂区");
                        return;
                    }
                    if (StringUtils.isEmpty(CheckNum)) {
                        ToastUtils.showShort("全检数不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(InspectorName)) {
                        ToastUtils.showShort("请选择巡检员");
                        return;
                    }
                    if (StringUtils.isEmpty(InspectTime)) {
                        ToastUtils.showShort("请选择检验日期");
                        return;
                    }
                    if (StringUtils.isEmpty(InspectTime)) {
                        ToastUtils.showShort("请选择检验日期");
                        return;
                    }
                    materialDialog = new MaterialDialog.Builder(this)
                            .content("提交数据中...")
                            .progress(true, 0)
                            .cancelable(false)
                            .show();
                    handler.sendEmptyMessage(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.pack_update_area:
                if (null != allAreaBean && null != allAreaBean.getData() && allAreaBean.getData().size() > 0) {
                    new MaterialDialog.Builder(this)
                            .items(allAreaBean.getData())
                            .itemsCallback((dialog, view1, position, text) -> {
                                pack_update_area.setText(allAreaBean.getData().get(position).getItemName());
                            })
                            .show();
                }
                break;
        }
    }

    private Handler handler = new Handler(message -> {
        String LoginName = ACache.get(this).getAsString("LoginName");
        String UserName = ACache.get(this).getAsString("UserName");
        LogUtils.e("message.what = " + message.what);
        switch (message.what) {
            case 0:
                presenter.getPackInfo(FlowingCode, LoginName);
                break;
            case 1:
                presenter2.getDefaultArea(LoginName);
                break;
            case 2:
                presenter2.getAllArea();
                break;
            case 5:
                LogUtils.e("LoginName = " + LoginName);
                LogUtils.e("UserName = " + UserName);
                LogUtils.e("Guid = " + Guid);
                LogUtils.e("ID = " + ID);
                LogUtils.e("cInvName = " + cInvName);
                LogUtils.e("cInvCode = " + cInvCode);
                LogUtils.e("Color = " + Color);
                LogUtils.e("PackQty = " + PackQty);
                LogUtils.e("Check_BZ = " + Check_BZ);
                LogUtils.e("CheckNum = " + CheckNum);
                LogUtils.e("FlowingCode = " + FlowingCode);
                LogUtils.e("Remark = " + Remark);
                LogUtils.e("Result = " + Result);
                LogUtils.e("InspectorName = " + InspectorName);
                LogUtils.e("InspectorCode = " + InspectorCode);
                LogUtils.e("InspectTime = " + InspectTime);
                LogUtils.e("FacArea = " + FacArea);
                LogUtils.e("DefectNum = " + DefectNum);
                LogUtils.e("DefectDes = " + DefectDes);
                LogUtils.e("IsReCheck = " + IsReCheck);
                presenter.update(LoginName,
                        UserName,
                        Guid,
                        ID,
                        cInvName,
                        cInvCode,
                        Color,
                        PackQty,
                        Check_BZ,
                        CheckNum,
                        FlowingCode,
                        Remark,
                        Result,
                        InspectorName,
                        InspectorCode,
                        InspectTime,
                        FacArea,
                        DefectNum,
                        DefectDes,
                        IsReCheck);
                break;
        }
        return false;
    });

    @Override
    public void onSuccess(PackInfoBean packInfoBean) {
        if (null != packInfoBean) {
            cInvName = packInfoBean.getCInvName();
            cInvCode = packInfoBean.getCInvCode();
            Color = packInfoBean.getColor();
            PackQty = packInfoBean.getPackQty();
            Check_BZ = packInfoBean.getCheck_BZ();
            pack_update_name.setText(cInvName);
            pack_update_pack.setText(PackQty);
            pack_update_color.setText(Color);
            pack_update_percent.setText(Check_BZ);
            try {
                double Check_BZ_num = Double.parseDouble(Check_BZ);
                double PackQty_num = Double.parseDouble(PackQty);
                int CheckNum_num = (int) Math.ceil(Check_BZ_num * PackQty_num / 100);
                pack_update_check.setText(String.valueOf(CheckNum_num));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            pack_update_percent.addTextChangedListener(new myTextWatcher());
        }
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        ToastUtils.showShort(baseBean.getMessage());
        setResult(BaseConstant.result_code);
        finish();
    }

    @Override
    public void onSuccess(HangUpdateLoginBean hangUpdateLoginBean) {
        try {
            FacArea = hangUpdateLoginBean.getData().get(0).getStaffArea();
            pack_update_area.setText(FacArea);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private AllAreaBean allAreaBean;

    @Override
    public void onSuccess(AllAreaBean allAreaBean) {
        this.allAreaBean = allAreaBean;
    }

    /**
     * 抽检比例输入监听
     */
    private class myTextWatcher extends BaseTextWatcher {

        @Override
        public void onTextChanged(String message) {
            try {
                PackQty = pack_update_pack.getText().toString();
                if (!StringUtils.isEmpty(message) && !StringUtils.isEmpty(PackQty)) {
                    double Check_BZ_num = Double.parseDouble(message);
                    double PackQty_num = Double.parseDouble(PackQty);
                    int CheckNum_num = (int) Math.ceil(Check_BZ_num * PackQty_num / 100);
                    pack_update_check.setText(String.valueOf(CheckNum_num));
                    LogUtils.e("计算");
                } else {
                    CheckNum = "";
                    pack_update_check.setText(CheckNum);
                    LogUtils.e("本包数或抽检比例为空，不计算");
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (BaseConstant.result_code == resultCode && null != data) {
            DefectDes = data.getStringExtra("DefectDes");
            DefectNum = data.getStringExtra("DefectNum");
            pack_update_desc.setText(DefectDes);
            pack_update_defect.setText(DefectNum);
        } else if (BaseConstant.result_scan == requestCode && null != data && null != data.getExtras()) {
            String result = FlowingUtils.getFlowing(data.getStringExtra(Intents.Scan.RESULT));
            if (StringUtils.isEmpty(result)) {
                ToastUtils.showShort("请填写流转单号");
            } else {
                LogUtils.e("result = " + result);
                FlowingCode = result;
                pack_update_flowing.setText(FlowingCode);
                handler.sendEmptyMessage(0); //根据流转单获取数据
            }
        }
    }
}